package com.ybg.share.core.report;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.type.AnnotationMetadata;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

/**
 * 手动扫描注册Bean 到Spring Context中，在jdbcmap.properties 配置文件中加入自己的JNDI即可。
 * 使用@Import(SpringBootJDBCBuildinDatasource.class) 再springboot启动类头部加上即可
 *
 * @author deament
 */
public class SpringBootJDBCBuildinDatasource implements ImportBeanDefinitionRegistrar {
    Logger logger = LoggerFactory.getLogger(SpringBootJDBCBuildinDatasource.class);

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {

        ClassPathResource resource = new ClassPathResource("jdbcmap.properties");
        EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
        try {
            Properties properties = PropertiesLoaderUtils.loadProperties(encodedResource);
            int count = 1;
            List<String> prefixs = getPrefixs(properties);
            for (String prefix : prefixs) {
                logger.info(prefix + ".username");
                String userName = properties.get(prefix + ".username").toString();
                String url = properties.get(prefix + ".url").toString();
                String password = properties.get(prefix + ".password").toString();
                String driver = properties.get(prefix + ".driver-class-name").toString();
                String name = properties.get(prefix + ".name").toString();
                DataSource druidDataSourse = getDruidDataSourse(url, userName, password, driver);
                BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(JDBCBuildinDataSource.class);
                builder.addPropertyValue("name", name);
                builder.addPropertyValue("dataSource", druidDataSourse);
                BeanDefinition beanDefinition = builder.getBeanDefinition();
                beanDefinitionRegistry.registerBeanDefinition("jDBCBuildinDatasource" + count, beanDefinition);
                count++;
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("jdbcmap.properties is not find");
            return;
        }


    }


    private DruidDataSource getDruidDataSourse(String url, String userName, String pwd, String driver) {
        DruidDataSource db = new DruidDataSource();
        db.setMinIdle(3000);
        db.setMaxActive(4000);
        db.setUrl(url);
        db.setUsername(userName);
        db.setPassword(pwd);
        db.setDriverClassName(driver);
        return db;
    }


    private List<String> getPrefixs(Properties properties) {
        List<String> prefixs = new ArrayList<>();
        Iterator<Object> iterator = properties.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next().toString();
            if (key.endsWith(".url")) {
                String prefix = key.split("\\.")[0];
                prefixs.add(prefix);
            }

        }
        return prefixs;
    }

    public static void main(String[] args) {
       System.out.println("aaa.url".split("\\.")[0].equals("aaa")); ;
    }

}

